<?php

namespace addons\cloud_market\controller\api;

use addons\cloud_market\model\CloudMarketProduct;
use addons\cloud_market\model\CloudMarketProductToken;
use addons\cloud_market\model\CloudMarketProductUser;

class Product extends CloudMarketApiController
{
    protected $notApiLogin = ['check_token'];

    /**
     * @var CloudMarketProduct
     */
    protected $model;

    /**
     * @var CloudMarketProductToken
     */
    private $tokenModel;

    /**
     * @var CloudMarketProductUser
     */
    private $userModel;

    /**
     * Token类型对应的时间配置（秒）
     * @var array
     */
    private $token_type_time = [
        0 => 365 * 86400,  // 年
        1 => 90 * 86400,   // 季
        2 => 30 * 86400,   // 月
        3 => 86400,        // 日
    ];

    protected function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketProduct();
        $this->tokenModel = new CloudMarketProductToken();
        $this->userModel = new CloudMarketProductUser();
    }

    /**
     * 获取用户产品列表
     * @return \think\response\Json
     */
    public function list()
    {
        $append = [];
        if (input("getAll") == "1") {
            $append = ["product", "expiredate", "createdate", "isexpire"];
        }

        $list = $this->userModel->where(['user_id' => $this->userInfo['id']])
            ->append($append)
            ->where("expiretime", ">", time())
            ->whereOr(['expiretime' => 0])
            ->select();

        return $this->success("ok", ["list" => $list]);
    }

    /**
     * 通过token激活产品
     * @param string $product_token 产品token
     * @param string $product_id 产品ID
     * @param string $product_mark 产品标识
     * @return \think\response\Json
     */
    public function activation($product_token = "", $product_id = "", $product_mark = "")
    {
        if (!$product_id && !$product_mark) {
            return $this->error("未指定产品");
        }

        $product = $this->model->where(['id' => $product_id])
            ->whereOr(['mark' => $product_mark])
            ->find();

        if (!$product) {
            return $this->error("产品不存在");
        }

        $product_id = $product['id'];
        $token_res = $this->tokenModel->where(["token" => $product_token])
            ->where(['product_id' => $product_id])
            ->find();

        if (!$token_res || $token_res['used'] == 1) {
            return $this->error("填写的token错误");
        }
        // 判断是否已经激活
        $product_user = $this->userModel->where(['user_id' => $this->userInfo['id'], 'product_id' => $product_id])
            ->findOrEmpty();

        if ($product_user['id']) {
            // 已激活
            if ($product_user['expiretime'] == 0) {
                return $this->error("您已经永久激活了该产品", $product_user);
            } else {
                $product_user->expiretime = $product_user['expiretime'] + $this->token_type_time[$token_res['type']];
                $product_user->save();
                $token_res->used = 1;
                $token_res->save();
                return $this->success("激活时间添加成功");
            }
        } else {
            // 未激活
            $data = [
                "user_id"    => $this->userInfo['id'],
                "product_id" => $product_id,
                "mark"       => $product['mark'],
                "token"      => $product_token,
                "expiretime" => time() + $this->token_type_time[$token_res['type']]
            ];
            $product_user->save($data);
            $token_res->used = 1;
            $token_res->save();
            return $this->success("激活成功");
        }
    }

    /**
     * 判断某产品是否有权限
     * @param string $product_mark 产品标识
     * @param int $product_id 产品ID
     * @return \think\response\Json
     */
    public function check($product_mark = "", $product_id = 0)
    {
        if (!$product_id && !$product_mark) {
            return $this->error('未指定产品');
        }

        $res = $this->userModel
            ->where(['user_id' => $this->userInfo['id']])
            ->where(['mark' => $product_mark])
            ->whereOr(['product_id' => $product_id])
            ->find();

        if (!$res) {
            return $this->error("没有该产品权限");
        } else {
            if ($res['expiretime'] != 0 && $res['expiretime'] <= time()) {
                return $this->error("当前产品已过期");
            }
            return $this->success("ok", $res);
        }
    }

    /**
     * 无需登录的token校验
     * @param string $token token
     * @param string $product_id 产品ID
     * @return \think\response\Json
     */
    public function check_token($token = '', $product_id = '')
    {
        $unique = input('unique', '');
        $edit = input("edit", 0);

        $_token = $this->tokenModel->where(['token' => $token, 'product_id' => $product_id])
            ->findOrEmpty();
        $_token['expiretime_text'] = date('Y-m-d H:i:s', $_token['expiretime']);

        if ($_token->isEmpty()) {
            return $this->error('token错误');
        }

        if ($edit == 1 && !empty($unique) && $_token['used'] == 1) {
            // 修改 unique
            $_token->unique = $unique;
            $_token->save();
        }

        if ($_token['used'] == 1 && $_token['unique'] != $unique) {
            return $this->error('唯一标识不正确');
        }

        if ($_token['used'] == 0) {
            // 未激活
            $_token->used = 1;
            $_token->unique = $unique;
            $_token->expiretime = time() + $this->token_type_time[$_token['type']];
            $_token->save();
            return $this->success("激活成功", $_token);
        }

        if ($_token['expiretime'] < time()) {
            return $this->error('产品已过期');
        }

        return $this->success('已激活', $_token);
    }
}
